package com.cg;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author cheyinbo
 * @description TODO
 * @date 2021/8/18 11:44
 */
public class JDKProxy01 {
    public static void main(String[] args) {
        JDKTeacherDao jdkTeacherDao = new JDKTeacherDaoImpl();
        ProxyFactory proxyFactory = new ProxyFactory(jdkTeacherDao);
        JDKTeacherDao proxyInstance = (JDKTeacherDao) proxyFactory.getProxyInstance();
        System.out.println(proxyInstance.getClass());
        System.out.println(proxyInstance.teach("张老师"));
    }
}

interface JDKTeacherDao {

    String teach(String teacherName);
}

class JDKTeacherDaoImpl implements JDKTeacherDao {

    @Override
    public String teach(String teacherName) {
        return teacherName + "正在教课...";
    }
}

class ProxyFactory {

    private final Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("代理开始");
                Object invoke = method.invoke(target, objects);
                System.out.println("代理结束");
                return invoke;
            }
        });
    }
}